﻿using B.S.DataBase.MyProject.Domain.Storages;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Read.API.Applicantions.Command.StoragesCommand;

namespace T.E.ERP.Read.API.Applicantions.CommandHandler.StoragesCommandHandler
{
    public class GetStorageHandler : IRequestHandler<GetStorageCommand, APIResult<ApiPaging<BaseStorage>>>
    {
        private readonly IBaseRepository<BaseStorage> _storageRepository;

        public GetStorageHandler(IBaseRepository<BaseStorage> storageRepository)
        {
            _storageRepository = storageRepository;
        }

        public Task<APIResult<ApiPaging<BaseStorage>>> Handle(GetStorageCommand request, CancellationToken cancellationToken)
        {
            //无条件查询
            APIResult<ApiPaging<BaseStorage>> result=new APIResult<ApiPaging<BaseStorage>>();
            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功.ToString();
            var list = _storageRepository.GetAll().Result;
            if (!string.IsNullOrEmpty(request.BaseCode))
            {
                list = list.Where(x => x.BaseCode.Contains(request.BaseCode));
            }
            if (!string.IsNullOrEmpty(request.BaseName))
            {
                list = list.Where(x => x.BaseName.Contains(request.BaseName));
            }
            int totalcount = list.Count();
            int totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.Pagesize);
            list = list.OrderByDescending(x => x.Cid).Skip((request.Pageindex - 1) * request.Pagesize).Take(request.Pagesize);
            ApiPaging<BaseStorage> paging = new ApiPaging<BaseStorage>();
            paging.TotalPage = totalpage;
            paging.TotalCount = totalcount;
            paging.list = list.ToList();
            result.data = paging;
            return Task.FromResult(result);
        }
    }
}
